package com.tecnap.app.activity;

import java.util.Iterator;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.tecnap.R;
import com.tecnap.app.LampEntity;
import com.tecnap.app.MapOverLayEntity;
import com.tecnap.app.database.ConfigDataSource;
import com.tecnap.app.database.LampDataSource;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

public class MapLampActivity extends MapActivity {

	private ConfigDataSource configDataSource;
	private LampDataSource lampDataSource;
	private MapView mapView;
	private MapController myMapController;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Database tables Connector
		configDataSource = new ConfigDataSource(this);
		lampDataSource = new LampDataSource(this);
		
		// Retrieve google api key
		configDataSource.open();
		String google_api_key = configDataSource.getConfig("google_api_key").getValue();
		configDataSource.close();
		
		// Initialize a new MapView
		mapView = new MapView(this, google_api_key);
		
		// Setup the MapView Layout
		LayoutParams params = new MapView.LayoutParams(
				LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT,
				null,
				LayoutParams.CENTER);
		mapView.setLayoutParams(params);
		
		mapView.setClickable(true);
		mapView.setBuiltInZoomControls(true);
		//mapView.setSatellite(true);
		
		myMapController = mapView.getController();
		
		// Open connection to Database
		lampDataSource.open();
		
		Float[] boundaries = lampDataSource.getMapBoundaries();
		if ((boundaries[1]-boundaries[0])<0.001){
			boundaries[1] = boundaries[1] + 0.0005f;
			boundaries[0] = boundaries[0] - 0.0005f;
			
		}
		if ((boundaries[3]-boundaries[2])<0.001){
			boundaries[3] = boundaries[3] + 0.0005f;
			boundaries[2] = boundaries[2] - 0.0005f;
			
		}
		GeoPoint center = new GeoPoint((int)((boundaries[1]+boundaries[0])*1000000/2), (int)((boundaries[2]+boundaries[3])*1000000/2));
		
		// Zooma e centra
		myMapController.zoomToSpan((int)((boundaries[1]-boundaries[0])*1100000), (int)((boundaries[3]-boundaries[2])*1100000));		
		myMapController.animateTo(center);
		
		setContentView(mapView);
		lampDataSource.close();
	}

	public void onResume() {
		super.onResume();
		// Check Internet Connection
		// ConnectivityManager connec =
		// (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

		// if (!connec.getNetworkInfo(0).isConnected()){
		final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
		if (!(activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED)) {
			// TODO Segnala errore e fermati
			AlertDialog dialog = new AlertDialog.Builder(this).create();
			dialog.setMessage("Sistema disconnesso!!!\n Attivare la connessione a Internet e riprovare.");
			dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog.show();
		}
		// Connection OK (!)

		// Open connection to Database
		lampDataSource.open();

		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(
				R.drawable.androidmarker);
		MapOverLayEntity itemizedoverlay = new MapOverLayEntity(drawable, this);

		// Load Lamp Points
		// Load All the Lamps from DB
		List<LampEntity> allLamps = lampDataSource.getAllLamps();
		Iterator<LampEntity> it = allLamps.iterator();

		while (it.hasNext()) {
			LampEntity le = it.next();
			GeoPoint point = new GeoPoint((int) (le.getPositionX() * 1E6),
					(int) (le.getPositionY() * 1E6));
			OverlayItem overlayitem = new OverlayItem(point, "Lamapada N° "
					+ le.getNumber().toString(), "Tipo: "
					+ le.getType().toString() + "\n " + "Potenza: "
					+ le.getPower().toString() + "\n " + "Marca: "
					+ le.getBrand().toString() + "\n " + "Modello: "
					+ le.getModel().toString());
			// Display point
			itemizedoverlay.addOverlay(overlayitem);
			mapOverlays.add(itemizedoverlay);
		}
		lampDataSource.close();
		
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

}
